package com.demo0228.demo01;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class SAXDemo {

    public static void main(String[] args) throws Exception {
        //先通过 DocumentBuilderFactory 创建一个 DocumentBuilder 实例
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        //DocumentBuilder 专门解析 XML 文档，解析后获得一个 Document 对象
        //该 Document 对象 代表被解析的 XML 文档
        Document document = documentBuilder.parse(SAXDemo.class.getResourceAsStream("/demo0228/books.xml"));
        //获取该 XML 文档的版本号
        System.out.println(document.getXmlVersion());
        //获取该 XML 文档的编码信息
        System.out.println(document.getXmlEncoding());

        NodeList bookList = document.getElementsByTagName("book");
        for (int i = 0; i < bookList.getLength(); i++) {
            Node bookNode = bookList.item(i);
            //获取节点名称
            System.out.println(bookNode.getNodeName());
            //获取属性集合
            NamedNodeMap attributes = bookNode.getAttributes();
            for (int j = 0; j < attributes.getLength(); j++) {
                Node item1 = attributes.item(j);
                System.out.println(item1.getNodeName() + " = " + item1.getNodeValue());
            }
            //获取 book 节点的所有子节点
            NodeList childNodes = bookNode.getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                Node item = childNodes.item(j);
                //                System.out.println(item.getNodeName() + " = " + item.getNodeValue());
                //判断是否属于标签节点
                if (item.getNodeType() == Node.ELEMENT_NODE) {
                    System.out.println("标签节点");
                    //获取节点标签名
                    String nodeName = item.getNodeName();
                    //获取节点文本内容
                    String textContent = item.getTextContent();
                    System.out.println(nodeName + " = " + textContent);
                }
            }

        }
    }
}
